#!/usr/local/bin/python
#encoding=gb2312

import os
import sys
import re
import gzip

import SysConfig
import Analysis

#store concerned gzfile;
g_list_gzfile = [];

#define concerned keyworks;
g_list_concerned_keyworkds = SysConfig.list_concerned_keyworkds;

#define concerned times
g_list_concerned_time = SysConfig.list_concerned_time;


g_sysAnalysis = Analysis.CAnalysis();

def getlogdir():
    return sys.path[0] + os.sep + '..' + os.sep;

#parse 

#parse file and process lines
def process_lines(szKeywords, szLines):
    global g_sysAnalysis;
    g_sysAnalysis.process_lines(szKeywords, szLines);
    


def parse_files_and_process_lines():
    global g_list_gzfile;
    for szFileName in g_list_gzfile:
        nLineNum = 0;
        listConcernedLines = [];
        szFullPath = getlogdir() + szFileName;
        
        gzipFile = gzip.open(szFullPath, 'r');
        for szLine in gzipFile:
            nLineNum = nLineNum + 1;
            for szKeywords in g_list_concerned_keyworkds:
                szPatter = '^' + szKeywords + '\|.*';
                m = re.match(szPatter, szLine);
                if m is not None:
                    print 'keywords[%s] matched file[%s] line[%d]' % (szKeywords, szFileName, nLineNum);
                    listConcernedLines.append((szKeywords,szLine));
        gzipFile.close();
        
        #process lines
        for obj in listConcernedLines:
            print 'process keywords[%s] line[%s]' % (obj[0],obj[1]);
            process_lines(obj[0], obj[1]);
            
        del listConcernedLines;
            
        
    return 0;

#genrate gz file list
def parse_gzfiles(strlogpath):
    global g_list_gzfile;
     
    listFiles = os.listdir(strlogpath);
    
    if len(listFiles) == 0:
        return -1;
    
    for szFileName in listFiles:
        m = re.match('^65535_(\d{8})_(\d{4})\.log\.gz', szFileName);
        if m is not None and len(m.groups()) == 2:
            nDay = int(m.groups()[0]);
            nTime = int(m.groups()[1]);
            if g_list_concerned_time[0][0] <= nDay and  \
            g_list_concerned_time[1][0] >= nDay and \
            g_list_concerned_time[0][1] <= nTime and  \
            g_list_concerned_time[1][1] >= nTime:
                print "match file:%s" % szFileName;
                g_list_gzfile.append(szFileName);
            
    return 0;


def main():
    szLogpath = getlogdir();
    nRet = parse_gzfiles(szLogpath);
    if nRet == -1:
        print 'parse gz file failed';
        return nRet;
    
    nRet = parse_files_and_process_lines();
    if nRet == -1:
        print 'extract line faied';
        return nRet;
    
    global g_sysAnalysis;
    g_sysAnalysis.output_log();
    
    
    return 0;

if __name__ == '__main__':
    main();
    
